package com.example.demo.controller;

import antlr.StringUtils;
import com.example.demo.entity.*;
import com.example.demo.mapper.MajorMapper;

import com.example.demo.mapper.UserMapper;
import com.example.demo.security.jwt.JwtTokenUtil;
import com.example.demo.service.AdminService;
import com.example.demo.service.UserService;
import com.example.demo.utils.CSVUtils;
import com.example.demo.utils.LoggerUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.DirectoryIteratorException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.logging.Logger;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    //管理员录入用户功能
    @PostMapping("/add")
    public Response add(@RequestParam String id,
                        @RequestParam String name,
                        @RequestParam String identityid,
                        @RequestParam String mail,
                        @RequestParam String phonenumber,
                        @RequestParam String role,
                        @RequestParam String uschool,
                        @RequestParam String umajor,
                        @RequestHeader("Authorization") String token) {
        if (!adminService.validateToken(token))
            return Response.ok(999, "非管理员用户登录");
        System.out.println("requestForm:" + name);
        return Response.ok(adminService.add(id, name, identityid, mail, phonenumber, role, uschool, umajor));
    }

    //管理员查询所有专业及其所属学院功能
    @GetMapping("/majorList")
    public Response findMajorAll(@RequestHeader("Authorization") String token) {
        List<Major> majors = adminService.majorFindAll();
        Integer num = majors.size();
        HashMap hashMap = new HashMap<>();
        hashMap.put("total", num);
        hashMap.put("res", majors);
        return Response.ok(200, "请求完成", hashMap);
    }

    //管理员查询所有学院及其下属专业功能
    @GetMapping("/schoolList")
    public Response findSchoolAll(@RequestHeader("Authorization") String token) {
        List<HashMap> schools = adminService.schoolFindAll();
        Integer num = schools.size();
        HashMap hashMap = new HashMap<>();
        hashMap.put("total", num);
        hashMap.put("res", schools);
        return Response.ok(200, "请求完成", hashMap);
    }

    //管理员查询某一个专业及其所属学院功能
    @GetMapping("/oneMajorFind")
    public Response findMajorOne(String mname) {
        if (Objects.equals(mname, ""))
            return Response.ok(999, "查询失败，专业名称为空");
        else {
            Major major = adminService.findMajorOne(mname);
            if (major == null)
                return Response.ok(500, "查询失败，专业不存在");
            return Response.ok(200, "请求完成", major);
        }
    }

    //管理员查询某一个学院及其下属专业功能
    @GetMapping("/oneSchoolFind")
    public Response findSchoolOne(String sname) {
        if (Objects.equals(sname, ""))
            return Response.ok(999, "查询失败，学院名称为空");
        else {
            School school = adminService.findSchoolOne(sname);
            if (school == null)
                return Response.ok(500, "查询失败，学院不存在");
            List<Major> majors = school.getMajors();
            Integer num = majors.size();
            HashMap hashMap = new HashMap<>();
            hashMap.put("major_total", num);
            hashMap.put("res", school);
            return Response.ok(200, "请求完成", hashMap);
        }
    }

    //管理员增加学院专业功能
    @PostMapping("/addMajor")
    public Response addMajor(@RequestParam String sname, @RequestParam String mname, @RequestHeader("Authorization") String token) {
        if (Objects.equals(sname, ""))
            return Response.ok(999, "增加失败，学院信息为空");
        return Response.ok(200, adminService.addMajor(sname, mname));
    }


    //管理员修改学院功能
    @PostMapping("/changeSchool")
    public Response changeSchool(String oldSname, String newSname) {
        if (Objects.equals(oldSname, "") || Objects.equals(newSname, "")) {
            return Response.ok(999, "请求失败，原学院或新学院信息缺失");
        }
        return Response.ok(200, adminService.changeSchool(oldSname, newSname));
    }


    //管理员修改专业功能
    @PostMapping("/changeMajor")
    public Response changeMajor(String newSname, String oldMname, String newMname) {
        if (Objects.equals(oldMname, "") || Objects.equals(newMname, "") || Objects.equals(newSname, "")) {
            return Response.ok(999, "请求失败，修改信息为空");
        }
        String res = adminService.changeMajor(newSname, oldMname, newMname);
        System.out.println(res);
        return Response.ok(200, res);
    }

    //管理员删除学院功能
    @PostMapping("/deleteSchool")
    public Response deleteSchool(String sname) {
        if (Objects.equals(sname, "")) {
            return Response.ok(999, "请求失败，学院名称为空");
        }
        return Response.ok(200, adminService.deleteSchool(sname));
    }

    //管理员删除专业功能
    @PostMapping("/deleteMajor")
    public Response deleteMajor(String mname) {
        if (Objects.equals(mname, "")) {
            return Response.ok(999, "请求失败，专业名称为空");
        }
        return Response.ok(200, adminService.deleteMajor(mname));
    }

    //批量上传用户
    @PostMapping(value = "/uploadUser")
    public Response upload(@RequestParam MultipartFile multipartFile) {
        try {
            System.out.println("uploadUser");

            //上传内容不能为空
            if (multipartFile == null) {
                System.out.println("file empty");
                return Response.ok(999, "上传内容为空");
            }
            System.out.println("uploadUser2");

            File file = CSVUtils.uploadFile(multipartFile);
            List<List<String>> userList = CSVUtils.readCSV(file.getPath(), 8);
            //file.delete();
            Files.delete(file.toPath());
            return Response.ok(200, "读取成功", adminService.addUsers(userList));
        } catch (Exception e) {
            LoggerUtils.log( "upload", e);

        }
        return Response.ok(500, "请求失败");
    }

    //管理员修改用户状态功能
    @PostMapping(value = "/changeStatus")
    public Response changeStatus(@RequestParam String uid, @RequestParam String ustatus) {
        HashMap hashMap = adminService.changeStatus(uid, ustatus);
        if (hashMap.get("error") != null) {
            return Response.ok(500, "修改失败", hashMap);
        }
        if (hashMap.get("warning") != null) {
            return Response.ok(501, "修改失败", hashMap);
        }
        return Response.ok(200, "修改成功", hashMap);
    }

    //管理员查询所有用户信息
    @GetMapping(value = "/userList")
    public Response userFindAll() {
        return Response.ok(200, "请求完成", adminService.userFindAll());
    }

    @PostMapping(value = "/changeUser")
    public Response changeUser(@RequestParam String id,
                               @RequestParam String newname,
                               @RequestParam String newidentityid,
                               @RequestParam String newmail,
                               @RequestParam String newphonenumber,
                               @RequestParam String newrole,
                               @RequestParam String newuschool,
                               @RequestParam String newumajor) {
        HashMap resMap = adminService.changeUserInfo(id, newname, newidentityid, newmail, newphonenumber, newrole, newuschool, newumajor);
        Object res = resMap.get("result");
        if (res == "success") {
            return Response.ok(200, "修改成功", resMap);
        } else {
            return Response.ok(500, "修改失败", resMap);
        }
    }

    //管理员获取选课功能状态
    @GetMapping(value = "/getXkStatus")
    public Response getXkStatus(@RequestHeader("Authorization") String token) {
        if (!Objects.equals(jwtTokenUtil.getUseridFromToken(token), "1001")) {
            return Response.ok(999, "没有权限");
        }
        String res = adminService.xkStatus();
        if (Objects.equals(res, "查询失败")) {
            return Response.ok(500, "查找不到选课功能");
        } else
            return Response.ok(200, res);
    }

    //管理员开启关闭选课开关功能
    @PostMapping(value = "/xkOpenClose")
    public Response xkOpenClose(@RequestParam String select, @RequestHeader("Authorization") String token) {
        String errMessage = null;
        boolean isCorrect = true;
        if (!Objects.equals(jwtTokenUtil.getUseridFromToken(token), "1001")) {
            errMessage="没有权限";
            isCorrect=false;
            //return Response.ok(999, "没有权限");
        }
        if (!Objects.equals(select, "true") && !Objects.equals(select, "false")) {
            errMessage = "请求失败，传参错误";
            isCorrect=false;
            //return Response.ok(999, "请求失败，传参错误");
        }
        if(!isCorrect)
            return Response.ok(999,errMessage);
        String res = adminService.xkOpenClose(select);
        if (Objects.equals(res, "更改失败")) {

            return Response.ok(500, "更改失败");
        } else {
            return Response.ok(200, res);
        }
    }

    //管理员管理课程时间(增加、修改)
    @PostMapping(value = "/arrangeSchedule")
    public Response arrangeSchedule(String scheduleList) {
        List<Schedule> schedules = new ArrayList<Schedule>();
        String schString = scheduleList;
        String errMsg = null;
        if (schString.isEmpty()) {
            errMsg = "内容为空";
        }
        JSONArray jsonArray = JSONArray.fromObject(schString);
        for (Object obj : jsonArray) {
            JSONObject jsonObject2 = JSONObject.fromObject(obj);
            Schedule schedule = (Schedule) JSONObject.toBean(jsonObject2, Schedule.class);
            schedules.add(schedule);
        }
        if (schedules.size() != 13) {
            errMsg = "数据长度不符";
        }
        if(errMsg!=null)
            return Response.ok(999,errMsg);
        Integer resCode = adminService.arrangeSchedule(schedules);
        if (resCode == 200)
            return Response.ok(200, "更新成功");
        else
            return Response.ok(500, "更新失败，数据有误");
    }

    //管理员获取课程时间
    @GetMapping(value = "/getSchedule")
    public Response getSchedule() {
        List res = adminService.getSchedule();
        if (res.size() == 1)
            return Response.ok(500, "查询不到结果");
        else
            return Response.ok(200, "查询成功", res);
    }

    //管理员获取所有楼栋
    @GetMapping(value = "/getBuildings")
    public Response getBuildings() {
        HashMap res = adminService.getBuildings();
        if (res.get("error") != null)
            return Response.ok(500, "查询不到结果");
        else
            return Response.ok(200, "查询成功", res);
    }

    //管理员获取所有教室
    @GetMapping(value = "/getRooms")
    public Response getRooms() {
        HashMap res = adminService.getRooms();
        if (res.get("error") != null)
            return Response.ok(500, "查询不到结果");
        else
            return Response.ok(200, "查询成功", res);
    }

    //管理员审核新增课程
    @PostMapping(value = "reviewAdd")
    public Response reviewAdd(@RequestParam String review,
                              @RequestParam int cid) {
        String result = adminService.reviewAdd(review, cid);
        return Response.ok(200, result);
    }

    //管理员审核删除课程
    @PostMapping(value = "reviewDelete")
    public Response reviewDelete(@RequestParam String review,
                                 @RequestParam int cid) {
        String result = adminService.reviewDelete(review, cid);
        return Response.ok(200, result);
    }

    //管理员审核删除课程
    @PostMapping(value = "reviewChange")
    public Response reviewChange(@RequestParam String review,
                                 @RequestParam int cid) {
        String result = adminService.reviewChange(review, cid);
        return Response.ok(200, result);
    }

    //批量导入课程
    @PostMapping(value = "/uploadCourse")
    public Response uploadCourse(@RequestParam MultipartFile multipartFile) {
        int colNum = 11;
        try {
            System.out.println("uploadCourse");

            //上传内容不能为空
            if (multipartFile == null) {
                System.out.println("file empty");
                return Response.ok(999, "上传内容为空");
            }
            System.out.println("uploadCourse2");

            File file = CSVUtils.uploadFile(multipartFile);
            List<List<String>> courseList = CSVUtils.readCSV(file.getPath(), colNum);
            Files.delete(file.toPath());
            return Response.ok(200, "读取成功", adminService.addCourses(courseList));
        } catch (Exception e) {
            LoggerUtils.log( "uploadCourse", e);
        }
        return Response.ok(500, "请求失败");
    }

    //请求所有待审批的课程
    @GetMapping(value = "/reviewCourseList")
    public Response reviewCourses() {
        return Response.ok(200, "查询结束", adminService.reviewCourseList());
    }

    //请求现有课程
    @GetMapping(value = "/courseList")
    public Response courseList() {
        return Response.ok(200, "查询结束", adminService.courseList());
    }

    //管理员新增课程
    @PostMapping("/addCourse")
    public Response addCourse(@RequestHeader("Authorization") String token,
                              @RequestBody com.alibaba.fastjson.JSONObject jsonObject) {
        String errMsg = null;
        if (!Objects.equals(jwtTokenUtil.getUseridFromToken(token), "1001")) {
            errMsg = "没有权限";
        }
        Course course = com.alibaba.fastjson.JSONObject.parseObject(jsonObject.toJSONString(), Course.class);

        String tid = jsonObject.get("tid").toString();

        if(userService.findUserById(tid)==null)
            errMsg = "教师不存在";
            //return Response.ok(999, "教师不存在");
        if(errMsg!=null)
            return Response.ok(999,errMsg);
        User teacher =userService.findUserById(tid);
        if(!teacher.getUstatus().equals("在岗"))
            return Response.ok(999,"该教师已离职");
        course.setCteacher(teacher.getName());
        HashMap result = adminService.addCourse(course, teacher);
        if (result.get("result") == "success")
            return Response.ok(200, "新增成功");
        return Response.ok(500, "新增失败", result);
    }


    //管理员修改课程
    @PostMapping("/changeCourse")
    public Response changeCourse(@RequestHeader("Authorization") String token,
                                 @RequestBody com.alibaba.fastjson.JSONObject jsonObject) {

        String tid = jsonObject.get("tid").toString();
        Course cCourse = com.alibaba.fastjson.JSONObject.parseObject(jsonObject.toJSONString(),Course.class);
        if(!userMapper.existsById(tid))
            return Response.ok(500,"不能修改");
        User teacher = userService.findUserById(tid);
        cCourse.setCstatus("normal");
        cCourse.setCteacher(teacher.getName());

        HashMap<String,String> result = adminService.changeCourse(cCourse,teacher);
        if(Objects.equals(result.get("result"), "success"))
            return Response.ok(200,"修改成功");
        else
            return Response.ok(500,"不能修改",result);
    }

    //删除课程
    @PostMapping("/deleteCourse")
    public Response deleteCourse(@RequestHeader("Authorization") String token, @RequestParam Integer cid){
        if(adminService.deleteCourse(cid)==200){
            return Response.ok(200,"删除成功");
        }
        else{
            return Response.ok(500,"课程信息错误");
        }
    }

    @PostMapping("/addRoom")
    public  Response addRoom(@RequestHeader("Authorization") String token,
                                @RequestParam String rname,
                                @RequestParam Integer capacity){
        if (!Objects.equals(jwtTokenUtil.getUseridFromToken(token), "1001")) {
            return Response.ok(999, "没有权限");
        }
        if(adminService.addRoom(rname,capacity)==200){
            return Response.ok(200,"新增成功");
        }
        else{
            return Response.ok(500,"该教室已存在");
        }
    }

    @PostMapping("/changeRoom")
    public  Response changeRoom(@RequestHeader("Authorization") String token,
                                @RequestParam String oldrname,
                                @RequestParam String newrname,
                                @RequestParam Integer newcapacity){
        if (!Objects.equals(jwtTokenUtil.getUseridFromToken(token), "1001")) {
            return Response.ok(999, "没有权限");
        }
        if(adminService.changeRoom(oldrname,newrname,newcapacity)==200){
            return Response.ok(200,"修改成功");
        }
        else{
            return Response.ok(500,"教室信息有误");
        }
    }

    @PostMapping("/deleteRoom")
    public  Response deleteRoom(@RequestHeader("Authorization") String token,
                                @RequestParam String rname){
        if (!Objects.equals(jwtTokenUtil.getUseridFromToken(token), "1001")) {
            return Response.ok(999, "没有权限");
        }
        if(adminService.deleteRoom(rname)==200){
            return Response.ok(200,"删除成功");
        }
        else{
            return Response.ok(500,"对应教室不存在或正在使用中");
        }
    }
}